﻿using System;
using Newtonsoft.Json.Linq;
using System.Text;
using Mangdot.Webchat.Models;
using System.Net;
using System.Net.Security;

namespace Mangdot.Webchat.Common
{
    public static class WebchatService
    {

        private static string _tokenUrl = "https://182.254.88.157/cgi-bin/token";
        private static string _createMemuUrl = "https://182.254.88.157/cgi-bin/menu/create?access_token=";
        private static string _jsapiticketUrl = "https://182.254.88.157/cgi-bin/ticket/getticket";
        private static string _authorizeUrl = "https://182.254.88.157/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_userinfo&state={2}#wechat_redirect";
        private static string _callbackUrl = "http://182.254.88.157/wechat/authorizecallback";
        private static string _userinfoUrl = "https://182.254.88.157/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN";
        private static string _accesstokenUrl = "https://182.254.88.157/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code";
        private static DateTime _takenExpridTime;
        private static string _token { get; set; }

        private static DateTime _jsapiTicketExpridTime { get; set; }
        private static string _jsapiTicket { get; set; }



        /// <summary>
        ///  随机字符串
        /// </summary>
        public static string NonceStr
        {
            get
            {
                return Security.RandomString(10, false);
            }
        }

        /// <summary>
        /// 时间戳
        /// </summary>
        public static string TimeStamp
        {
            get
            {
                TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                return Convert.ToInt64(ts.TotalSeconds).ToString();
            }
        }


        public static string GetToken()
        {
            try
            {
                if (_takenExpridTime.AddHours(2) > DateTime.Now)
                    return _token;

                var pString = string.Format("grant_type=client_credential&appid={0}&secret={1}", WXConfig.AppId, WXConfig.AppSecret); //JsonConvert.SerializeObject(p);

                //ssl证书
                ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
                ServicePointManager.ServerCertificateValidationCallback = new
                RemoteCertificateValidationCallback
                (
                   delegate { return true; }
                );


                var respData = Common.RerestService.Get(_tokenUrl, pString);
                Logger.Info("Token:" + respData);
                var jObject = JObject.Parse(respData);

                var token = jObject.GetValue("access_token").ToString();
                if (!string.IsNullOrEmpty(token))
                {
                    _takenExpridTime = DateTime.Now;
                    _token = token;
                    return token;
                }
            }
            catch (Exception e)
            {
                Logger.Error("GetToken is error!", typeof(WebchatService), e);
            }

            return string.Empty;
        }

        public static string CreateMenu()
        {

            string url = _createMemuUrl + GetToken();
            StringBuilder sb = new StringBuilder();
            sb.Append("{ \"button\":[");
            sb.Append("{\"name\":\"服务\",\"sub_button\":[{	\"type\":\"pic_sysphoto\",\"name\":\"拍照\",\"key\":\"TAKEPHOTO\"},{	\"type\":\"scancode_push\",\"name\":\"扫一扫\",\"key\":\"SCAN\" },{	\"type\":\"click\",\"name\":\"物联网\",\"key\":\"IOT\" },{	\"type\":\"view\",\"name\":\"微信接口\", \"url\":\"http://203.195.235.76/jssdk\" }]},");
            sb.Append("{\"name\":\"贺卡\",\"sub_button\":[{	\"type\":\"view\",\"name\":\"发贺卡\",\"url\":\"http://wx.mangdot.com/HEKA/index.html\"},{	\"type\":\"view\",\"name\":\"制作贺卡\",\"url\":\"http://wx.mangdot.com/home/index\"}]},");
            sb.Append("{\"name\":\"联系我们\",\"type\":\"click\",\"key\":\"Contact\"}");
            sb.Append("]}");
            var respData = Common.RerestService.Post(url, sb.ToString());
            Logger.Info("创建菜单：" + respData);
            var jObject = JObject.Parse(respData);
            return respData;
        }


        #region JS-SDK

        public static string GetJsApiTicket()
        {
            if (_jsapiTicketExpridTime.AddHours(2) > DateTime.Now)
                return _jsapiTicket;

            string tokenAccess = GetToken();
            string p = string.Format("access_token={0}&type=jsapi", tokenAccess);
            var respData = Common.RerestService.Get(_jsapiticketUrl, p);

            var jObject = JObject.Parse(respData);

            var ticket = jObject.GetValue("ticket").ToString();

            if (!string.IsNullOrEmpty(ticket))
            {
                _jsapiTicket = ticket;
                _jsapiTicketExpridTime = DateTime.Now;
                return ticket;
            }
            return string.Empty;
        }

        /// <summary>
        /// 获取页面验证JS-SDK 参数
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static SDKConfig GetWXConfig(string url)
        {
            var jsapi_ticket = GetJsApiTicket();
            Logger.Trace("ticket:" + jsapi_ticket);

            string[] arrayP = { "noncestr=" + NonceStr, "jsapi_ticket=" + jsapi_ticket, "timestamp=" + TimeStamp, "url=" + url };
            Array.Sort(arrayP);

            string tmpStr = string.Join("&", arrayP);
            Logger.Trace("keyvalues" + tmpStr);
            string signature = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
            Logger.Trace("encry:" + signature);
            string timep = TimeStamp;

            return new SDKConfig
            {
                appId = WXConfig.AppId,
                signature = signature,
                nonceStr = NonceStr,
                timestamp = timep
            };

        }

        #endregion

        #region Authorize

        public static string GetCode()
        {
            try
            {
                var url = string.Format(
                    _authorizeUrl,
                    WXConfig.AppId,
                    System.Web.HttpContext.Current.Server.UrlEncode(_callbackUrl),
                    NonceStr
                    );
                Logger.Trace(url);
                return url;
            }
            catch (Exception e)
            {
                Logger.Error("GetCode is error!", typeof(WebchatService), e);
            }

            return string.Empty;
        }


        public static string GetUserInfo(string code)
        {
            var respData = Common.RerestService.Get(string.Format(_accesstokenUrl, WXConfig.AppId, WXConfig.AppSecret, code));
            var jObject = JObject.Parse(respData);
            Logger.Trace(jObject.ToString());


            var userInfo = RerestService.Get(string.Format(_userinfoUrl, jObject.GetValue("access_token").ToString(), jObject.GetValue("openid").ToString()));
            Logger.Trace(userInfo);
            var userObject = JObject.Parse(userInfo);
            return userObject.GetValue("openid").ToString();
        }


        #endregion
    }


}